#!/bin/bash

# Set up command recording wrapper

[ -z "$WRAPDIR" ] && WRAPDIR="$PWD"/record-commands && RM=$(which rm)
[ -z "$WRAPLOG" ] && export WRAPLOG="$PWD"/log.txt

if [ $# -eq 0 ]
then
  echo "usage: WRAPDIR=dir WRAPLOG=log.txt record-commands COMMAND..."
  echo 'Then examine log.txt. "record-commands echo" to just setup $WRAPDIR'
  exit 1
fi

if [ ! -x "$WRAPDIR/logwrapper" ]
then
  make logwrapper
  mkdir -p "$WRAPDIR" && mv logwrapper "$WRAPDIR" || exit 1

  echo "$PATH" | tr : '\n' | while read DIR
  do
    ls "$DIR/" | while read FILE
    do
      ln -s logwrapper "$WRAPDIR/$FILE" 2>/dev/null
    done
  done
fi

# Delete old log (if any)
rm -f "$WRAPLOG"

X=0
if [ ! -z "$1" ]
then
  PATH="$WRAPDIR:$PATH" "$@"
fi
X=$?
[ ! -z "$RM" ] && "$RM" -rf "$WRAPDIR"

exit $X
